/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.lastproject;
import Server.Helper.StringHelper;
import Server.MyDataType.*;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
/**
 *
 * @author CANG
 */
public class ServerForm  extends JFrame implements ActionListener
{
    public final static String TABLE_CREATE = "Table Create";                        
    public final static String TABLE_STRUCT = "Table Struct";
    public final static String TABLE_DATA = "Table Data";
    public final static String TABLE_DATA_EDIT = "Table Data Edit";            
    
   
    private JPanel _jpContainerTable;
    private JPanel _jpContainerTree;
    private JTable _jtUpdateStructTable;
    private JTable _jtDataRow;

    private DefaultTableModel _dtmCreateTable;
    private JTree _jtListDatabase;
    private JScrollPane _jscpListDatabase;
    DefaultMutableTreeNode _defaultMutableTreeNode;
    DefaultTreeModel _defaultTreeModel;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItemStart;
    private javax.swing.JMenuItem jMenuItemStop;
    private javax.swing.JMenuItem jMenuItemExit;
    private XMLManage _xmlManage;

    private TableData_StructClickLisstener _clTableStruct;
    private  RowDataStructListener _clDataStruct;
    
    private String _sNameTableCurrent = "null";
    private final JSplitPane jSplitPane1;
    private JTabbedPane jTabbedPane1;
    private ServerListen serverListen;
    
    public ServerForm()
    {        
        
        _xmlManage = new XMLManage();
        jTabbedPane1 = new javax.swing.JTabbedPane();
     
        _jpContainerTree = new JPanel();
           jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItemStart = new javax.swing.JMenuItem();
        jMenuItemStop = new javax.swing.JMenuItem();
        jMenuItemExit= new javax.swing.JMenuItem();

        _jscpListDatabase = new JScrollPane();
        _defaultMutableTreeNode = new DefaultMutableTreeNode("DATABASE");
        _defaultTreeModel = new DefaultTreeModel(_defaultMutableTreeNode);
        _jtListDatabase = new JTree(_defaultTreeModel);
        _jpContainerTable = new JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();

        _jtUpdateStructTable = new JTable()
        {
            public Dimension getPreferredScrollableViewportSize()
            {
                    return getPreferredSize();
            }
        };
        
    
         StartServer();
        
        
        addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent winEvt) {
                Exit();
            }
        });
        
     
              
       
       
        initComponent();
    }

    private void CloseTab(String NameTable) {
        for(int i = 0;i<jTabbedPane1.getTabCount();i++)
               if(jTabbedPane1.getTitleAt(i).equals(NameTable))
               {
                  jTabbedPane1.remove(i);
                 
               }
    }
    
    private void initComponent()
    {
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
         jTabbedPane1.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        _jpContainerTree.setBackground(new java.awt.Color(153, 204, 255));
        _jpContainerTree.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        _jscpListDatabase.setViewportView(_jtListDatabase);
        _jtListDatabase.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                _jtListDatabaseMouseClicked(evt);
            }

           
        });
         _jpContainerTree.setMinimumSize(new java.awt.Dimension(150, 0));
        javax.swing.GroupLayout _jpContainerTreeLayout = new javax.swing.GroupLayout(_jpContainerTree);
        _jpContainerTree.setLayout(_jpContainerTreeLayout);
        _jpContainerTreeLayout.setHorizontalGroup(
            _jpContainerTreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 148, Short.MAX_VALUE)
            .addGroup(_jpContainerTreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(_jpContainerTreeLayout.createSequentialGroup()
                    .addComponent(_jscpListDatabase, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        _jpContainerTreeLayout.setVerticalGroup(
            _jpContainerTreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 506, Short.MAX_VALUE)
            .addGroup(_jpContainerTreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(_jscpListDatabase, javax.swing.GroupLayout.DEFAULT_SIZE, 506, Short.MAX_VALUE))
        );
        jSplitPane1.setLeftComponent(_jpContainerTree);
                    

   
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(_jpContainerTable);
        _jpContainerTable.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 833, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 833, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 508, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 506, Short.MAX_VALUE)
                    .addGap(2, 2, 2)))
        );
        jSplitPane1.setRightComponent(_jpContainerTable);
        
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 990, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 990, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 510, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE))
        );
        
        
        
         //<editor-fold defaultstate="collapsed" desc=" init Menu ">
      
       jMenu1.setText("File");

        jMenuItemStart.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItemStart.setText("Start Listen");
        jMenuItemStart.addActionListener(this);
        jMenu1.add(jMenuItemStart);

        jMenuItemStop.setText("Stop Listen");
        jMenu1.add(jMenuItemStop);
        jMenuItemStart.addActionListener(this);

        jMenuItemExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItemExit.setText("Exit");
        jMenuItemExit.addActionListener(this);
        jMenu1.add(jMenuItemExit);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);
        //</editor-fold>
        this.setTitle("Server Database");
        pack();
        
        TreeTableClickListener lis = new TreeTableClickListener(_jtUpdateStructTable, this);
        _jtListDatabase.addMouseListener(lis);
        LoadDataTable();
                
//        _clTableStruct = new TableData_StructClickLisstener(_jtUpdateStructTable, this);        
        _jtUpdateStructTable.addMouseListener(_clTableStruct);
        _jtUpdateStructTable.setVisible(false);
        
       // _clDataStruct = new RowDataStructListener(_jtDataRow, this);

        
    }
    
    public void LoadDataTable()
    {
       
        _defaultMutableTreeNode = new DefaultMutableTreeNode("DATABASE");
        _defaultTreeModel.setRoot(null);
        _defaultTreeModel.setRoot(_defaultMutableTreeNode);
        
        
        _defaultTreeModel.setRoot(_defaultMutableTreeNode);
       String[] sNameTable = _xmlManage.getListNameTable();
             
       for(int i = 0; i < sNameTable.length; i++)
       {
           DefaultMutableTreeNode node_Table = new DefaultMutableTreeNode(sNameTable[i]);
          _defaultTreeModel.insertNodeInto(node_Table, _defaultMutableTreeNode, i);
       }
       
       expandAllListTable();
       
    }
    
    private void expandAllListTable()
    {
        int iRowCount = _jtListDatabase.getRowCount();
        for (int i = 0; i < iRowCount; i++)
        {
            _jtListDatabase.expandRow(i);
        }
    }
     private void _jtListDatabaseMouseClicked(MouseEvent evt) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) _jtListDatabase.getLastSelectedPathComponent(); 
                if(node != null && node.isLeaf())
                {
                    TabInfo info = new TabInfo(this,node.toString());
                    info.SetUpdateStrucTable();
                    ShowInfo(ServerForm.TABLE_DATA, node.toString());
                }
            }
    public void ShowInfo(String typeShow, String nameTable)
    {        
       
        if(typeShow.equals(ServerForm.TABLE_STRUCT))
        {   
            
            TabInfo info = new TabInfo(this,nameTable);
            info.SetUpdateStrucTable();
            
            MyStructTable structTable = _xmlManage.getStructTable(nameTable);
            String sPrimaryKey = structTable._sPrimaryKey;
            
            int iAmountColumn = structTable._vtAttribute.size();
            for(int i = 0; i < iAmountColumn; i++)
            {
               Attribute_Value attribute_Column = structTable._vtAttribute.elementAt(i);
               String bPrimaryKey = "FALSE";
               if(attribute_Column.NameAttribute.equals(sPrimaryKey))
                   bPrimaryKey = "TRUE";
               
               String[] sNewRow = {attribute_Column.NameAttribute, attribute_Column.Type, bPrimaryKey};
               info.ModelTable.addRow(sNewRow);
               
            }  
            if(info.ModelTable.getRowCount() > 1)
                info.ModelTable.removeRow(0);
            CreateTab(nameTable, info.jTable,2,2);
           
        
        }
        else
        {
            if(typeShow.equals(ServerForm.TABLE_DATA_EDIT))
            {
               
                fillDataTable(nameTable,true);
                
            }
            else
            {
                if(typeShow.equals(ServerForm.TABLE_CREATE))
                {

                    TabInfo info = new TabInfo(this,nameTable);
                    info.SetCreateStrucTable();
                    CreateTab("New Table", info.jTable,1,1);   
                    
                }
                else
                {
                                      
                    fillDataTable(nameTable,false);
                    

                }
            }            
        }
    }
    
    public boolean fillDataTable(String nameTable, boolean edit)
    {
        try
        {    
           
            _xmlManage = new XMLManage();    
            TabInfo info = new TabInfo(this,nameTable);
            
            MyDataDynamic myData = getDataTable(nameTable);
            //myData._vtNameColumn.add("ID");
            Vector<String> vtNameColumn = myData._vtNameColumn;
            vtNameColumn.add("ID");
            String[] sHeaderNameColumn = StringHelper.convertToArray( vtNameColumn);    
            setTypeTable(sHeaderNameColumn, info.jTable);
            int iAmountColumn = myData._vtNameColumn.size();
                        
            int iAmoutRow = myData._vtRowData.size();
            for(int i = 0; i < iAmoutRow; i++)
            {
                MyRowData rowData = myData._vtRowData.elementAt(i);  
                rowData._vtRow.add( rowData.ID );
                String[] sData = StringHelper.convertToArray( rowData._vtRow);
                info.ModelTable.addRow(sData);                
            }
            
            if(iAmoutRow == 0)
            {                
                String[] sData = new String[iAmountColumn];
                sData[iAmountColumn - 1] = String.valueOf( _xmlManage.createID(nameTable));
                info.ModelTable.addRow( sData );
            }
            
            info.jTable.removeColumn(info.jTable.getColumnModel().getColumn(iAmountColumn - 1));
             if(edit)
             {
                 info.SetTableEditData(_xmlManage, nameTable);
                 CreateTab(nameTable, info.jTable,3,3);
             }
             else
             {
                 info.SetSelectData();
                 CreateTab(nameTable, info.jTable,3,0);
             }
            
        }
        catch(Exception ex)
        {
            return false;
        }
        return true;
    }
    
    public boolean createTable(MyStructTable structTable, String nameTable)
    {
        boolean bCreateTable = false;
        
        bCreateTable = _xmlManage.createTable(structTable, nameTable);
        if(bCreateTable)
        {
            CloseTab("New Table");
            ShowInfo(TABLE_STRUCT, nameTable.toUpperCase());
        }
        return bCreateTable;
    }
    public boolean DropTable(String nameTable)
    {
        boolean bCreateTable = false;
        
        bCreateTable = _xmlManage.deleteTable(nameTable);
        if(bCreateTable)
            LoadDataTable();
        return bCreateTable;
    }
    public void CreateTab(String NameTable, JTable jTable, int LenhKhiDong,int Prefix)
    {
         switch(Prefix)
         {
             case 1:
               
                 
             case 2:
                 
                 break;
             case 3:
                 NameTable = "[Edit data] "+NameTable;
                 break;
             case 0:
                 NameTable = "[select data] "+NameTable;
                 break;
         }
         CloseTab(NameTable);
         JScrollPane jScrollPane = new JScrollPane(jTable);
         jTabbedPane1.add(NameTable,jScrollPane);
         jTabbedPane1.setTabComponentAt(jTabbedPane1.getTabCount()-1,
         new ButtonTabComponent(jTabbedPane1,jTable,this,LenhKhiDong,NameTable));
         jTabbedPane1.setSelectedIndex(jTabbedPane1.getTabCount()-1);
    }
    public boolean deleteData(TableModel model)
    {
        try
        {
            int iCountData = model.getRowCount();
            for(int i = iCountData - 1; i >= 0; i--)
            {
                ((DefaultTableModel)model).removeRow(i);
            }
        }
        catch(Exception ex)
        {
            return false;
        }
        return true;
    }
    
    
    
    public boolean updateStructTable(MyStructTable structTable, String nameTable)
    {
        boolean bUpdate = _xmlManage.updateStructTable(structTable, nameTable);
        return bUpdate;
    }
    
    public MyStructTable getMyStructTable(TableModel model)
    {
        MyStructTable myStructTable = new MyStructTable();
        int iRow = model.getRowCount();
        
        String sIsPrimaryKey = "null";        
        
        
        for(int i = 0; i < iRow; i++)
        {
            Attribute_Value attribute = new Attribute_Value();            
            attribute.NameAttribute = (String)model.getValueAt(i, 0);
            attribute.Type = (String)model.getValueAt(i, 1);  
            if( attribute.NameAttribute != null)
                attribute.Value = attribute.NameAttribute.toUpperCase();
            
            if( attribute.NameAttribute == null || attribute.Type == null)
            {
                continue;
            }                
            String svalidPrimaryKey = model.getValueAt(i, 2).toString().toUpperCase();       
            
            if(svalidPrimaryKey.equals("TRUE"))
                sIsPrimaryKey = attribute.NameAttribute;
                        
            myStructTable._vtAttribute.add(attribute);
        }
        myStructTable._sPrimaryKey = sIsPrimaryKey;
        return myStructTable;
    }
    
    public boolean updateDataRow(String nameTable, Vector<MyRowData> lstRowData)
    {
        boolean bUpdate = _xmlManage.updateDataTable(nameTable, lstRowData);
        return bUpdate;
    }
    
    public boolean deleteColumnStruct(String nameTable, String nameColumn)
    {
        boolean bDelete = _xmlManage.deleteColumn(nameTable, nameColumn);
        return bDelete;
    }
    
    public boolean setTypeTable(String[] sHeaderNames, JTable jTable)
    {        
        try
        {
            DefaultTableModel model = (DefaultTableModel)jTable.getModel();
            
            model.setDataVector(null, sHeaderNames);
            _jtDataRow.setModel(model);
        }
        catch(Exception ex)
        {
            return false;
        }        
        return true;        
    }
    
    public MyDataDynamic  getDataTable(String nameTable)
    {
        MyDataDynamic myData = _xmlManage.getMyDataDynamic(nameTable);
        return myData;
    }
    
    public boolean deleteDataRow(String nameTable, String id)
    {
        boolean bDelete = true;
        try
        {
            bDelete = _xmlManage.deleteDataRow(nameTable, id);
        }
        catch(Exception ex)
        {
            return false;
        }
        
        return bDelete;
    }
    

    public void Exit() {
        // Perhaps ask user if they want to save any unsaved files first.
        int result = JOptionPane.showConfirmDialog(this, "Bạn chắc muốn thoát không?", "Server", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (result == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
    private void StartServer()
    {
        serverListen =  new ServerListen(this);
        serverListen.start();
        jMenuItemStart.setVisible(false);
        jMenuItemStop.setVisible(true);
    }
    public void StopServer()
    {         
        serverListen.stop();
        serverListen = null;
         jMenuItemStart.setVisible(true);
        jMenuItemStop.setVisible(false);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jMenuItemExit) {
            Exit();
        }
         if (e.getSource() == jMenuItemStart) {
            StartServer();
        }
          if (e.getSource() == jMenuItemStop) {
            StopServer();
        }
         
    }
    public static void main(String[] args) 
    {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException  ex)
        {
            System.out.print("error");
        }
        //</editor-fold>
       
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ServerForm().setVisible(true);
            }
        });
      
    }
}
